Custom Hook : Simplify Code with Reusable Logic

The custom hook in React allows to write data-fetching logic once and reuse it across multiple components.


Setting up a reusable data-fetching function to simplify API calls and state management.

State Initialization with useState:

It initializes a data state variable with null as the default value, using React's useState hook. This variable will hold the fetched data.

import { useState, useEffect } from 'react';

function useFetch(url) {
    const [data, setData] = useState(null);
        // rest of the logic
}

Fetching Data with useEffect:

The useEffect hook runs whenever the url changes. It performs a fetch request to the specified url, parses the response as JSON, and updates data with the fetched result.

useEffect(() => {
        fetch(url)
                .then(response => response.json())
                .then(setData);
}, [url]);

Returning Data:

Finally, the function returns the data state variable so it can be used directly in any component that calls useFetch.

import { useState, useEffect } from 'react';

function useFetch(url) {
    const [data, setData] = useState(null);

    useEffect(() => {
        fetch(url)
            .then(response => response.json())
            .then(setData);
    }, [url]);

    return data;
}

Usage

const data = useFetch('https://api.example.com/data');

You Might Also Like

How to Use Error Boundaries to Handle Errors

## 1. Define an ErrorBoundary class component ``` class ErrorBoundary extends React.Component { //...

Using useMemo for Caching and Optimizing Performance

~~`useMemo`~~ is a React Hook that helps optimize performance by memoizing (caching) the result of a...